<?php
namespace User\Controller;
use Org\Util\String;
use Think\Controller;
use Think\Model\RelationModel;

class IndexController extends Controller {
    public function _initialize(){
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:GET');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }

    /**
     * 密码登录
     * 参数：username、password
     * 说明：username可以为账号也可以为phonenumber
     */
    public function passwordLogin(){
        $username = I('post.username');
        $password = I('post.password');
        $user_model = M('user');
        $user_info = $user_model->where(['username'=>$username,'phonenumber'=>$username,'_logic'=>'or'])->find();
        //判断账号是否存在
        if(!$user_info){
            $result = [
                'status'=>'0',
                'message'=>'用户名不存在',
                'token'=>'',
            ];
            $this->ajaxReturn($result);exit;
        }
        //验证密码
        if($user_info['password'] != salt_mcrypt($password,$user_info['salt'])){
            $result = [
                'status'=>'0',
                'message'=>'密码错误',
                'token'=>'',
            ];
            $this->ajaxReturn($result);exit;
        }
        //验证成功 可登录
        $result = [
            'status'=>'1',
            'message'=>'登录成功',
            'token'=>$user_info['token'],
        ];
        $this->ajaxReturn($result);
    }

    /**
     *点击绑定字母账号接口    加上点击修改密码
     * 参数：token ident(标识B绑定，U修改)
     * 说明：返回当前用户的手机号 用于前端显示手机号
     */
    public function bindingUsername($token,$ident){
        //根据token获取用户信息
        $user_info = M('User')->where(['token'=>$token])->find();
        if(!$user_info){
            $result = [
                'status'=>'0',
                'message'=>'请登录',
                'phone'=>'',
            ];
            $this->ajaxReturn($result);exit;
        }
        //判断是绑定账号还是修改密码
        switch ($ident){
            case "B"://绑定
                if($user_info['username']){
                    $result = [
                        'status'=>'0',
                        'message'=>'你已经绑定过账号了',
                        'phone'=>'',
                    ];
                }else{
                    //返回替换为135***555的形式手机号
                    $phone = preg_replace('/(\d{3})\d{5}(\d{3})/','$1***$2',$user_info['phonenumber']);
                    $result = [
                        'status'=>'1',
                        'message'=>'获取成功',
                        'phone'=>$phone,
                    ];
                }
                break;
            case "U"://修改密码
                //返回替换为135***555的形式手机号
                $phone = preg_replace('/(\d{3})\d{5}(\d{3})/','$1***$2',$user_info['phonenumber']);
                $result = [
                    'status'=>'1',
                    'message'=>'获取成功',
                    'phone'=>$phone,
                ];
                break;
        }
        $this->ajaxReturn($result);
    }

    /**
     * 手机账号 绑定字母账号 发送短信验证码
     * 参数：token
     * 说明：当用户选择绑定字母账号时，跳转到绑定页面，点击发送短信验证码调用此接口
     */
    public function bindingUsernameSend($token){
        //根据token获取用户信息
        $user_info = M('User')->where(['token'=>$token])->find();
        //向当前绑定的用户发送短信验证码
        $code = new \Message\Controller\IndexController();
        cookie($user_info['phonenumber'], mt_rand(1000, 9999));
        $code->sendDayuSmsPlus($user_info['phonenumber'],(string)cookie($user_info['phonenumber']));//发送短信
        $result = array(
            'message' => '已发送验证码',
        );
        $this->ajaxReturn($result);
    }

    /**
     * 验证手机验证码
     * 参数：token
     * 说明：验证手机号码
     */
    public function bindingUsernameCheckedCode($token,$code){
        //根据token获取用户信息
        $user_info = M('User')->where(['token'=>$token])->find();
        if(checkedPhoneCode($user_info['phonenumber'],$code)){
            $result = ['status'=>1,'message'=>'验证成功'];
        }else{
            $result = ['status'=>0,'message'=>'验证失败'];
            cookie($user_info['phonenumber'],null);
        }
        $this->ajaxReturn($result);
    }

    /**
     * 绑定字母账号
     * 参数：username、password、repassword、token、pid
     * 说明：账号必须以字母开头（不少于6位不多于32位），密码（不少于6位不多于32位），pid加密
     */
    public function bindingUsernameMessage($pid,$username,$password,$repassword,$token){
//        var_dump(md5(date('YmdH',time()).md5('ola')));exit;
        //验证秘钥：
        if($pid != md5(date('YmdH',time()).md5('ola'))){
            $this->ajaxReturn(['status'=>'0']);exit;
        }
        //根据token获取用户信息
        $user_info = M('User')->where(['token'=>$token])->find();
        if($user_info['username']){
            $this->ajaxReturn(['status'=>0,'message'=>'已经绑定过账号了',]);exit;
        }
        if($password != $repassword){
            $this->ajaxReturn(['status'=>0,'message'=>'两次密码不相同']);exit;
        }
        $res = M('User')->where(['username'=>$username,'phonenumber'=>$username,'_logic'=>'or'])->find();
        if($res){
            $this->ajaxReturn(['status'=>0,'message'=>'该账号已存在']);exit;
        }
        //随机生成长度为6的盐
        $salt = String::randString(6);
        $password = salt_mcrypt($password,$salt);
        $data = [
            'password'=>$password,
            'username'=>$username,
            'salt'=>$salt,
        ];
        if(M('User')->where(['token'=>$token])->save($data)){
            $this->ajaxReturn(['status'=>1,'message'=>'绑定成功']);exit;
        }else{
            $this->ajaxReturn(['status'=>0,'message'=>'绑定失败']);exit;
        }
    }

    /**
     * 修改密码
     * 参数：token、password、repassword
     * 说明：密码（不少于6位不多于32位）
     */
    public function updatePassword($token,$pid,$password,$repassword){
//        var_dump(md5(date('YmdH',time()).md5('ola')));exit;
        //验证秘钥：
        if($pid != md5(date('YmdH',time()).md5('ola'))){
            $this->ajaxReturn(['status'=>'0']);exit;
        }
        if($password != $repassword){
            $this->ajaxReturn(['status'=>'0','message'=>'两次输入的密码不相同']);exit;
        }
        //随机生成长度为6的盐
        $salt = String::randString(6);
        $password = salt_mcrypt($password,$salt);
        $data = [
            'password'=>$password,
            'salt'=>$salt,
        ];
        if(M('User')->where(['token'=>$token])->save($data)){
            $this->ajaxReturn(['status'=>1,'message'=>'修改成功']);exit;
        }else{
            $this->ajaxReturn(['status'=>0,'message'=>'修改失败']);exit;
        }

    }

    /**
     * 注册+登录
     * 手机直接登录，如果没有该用户，直接注册
     */
    public function login(){
        $phonecode= I('phonecode');
        $usermodel = M('user');
//        //测试用
//        if( I('phonenumber')=="18883986242" && I('phonecode')=="1234")
//        {
//            $tokenfromdb= $usermodel->where(array('phonenumber'=>I('phonenumber')))->select();
//            $result=array(
//                'code'=>'1',
//                'message'=>'登录成功',
//                'token'=>$tokenfromdb[0]['token']
//            );
//            echo json_encode($result,JSON_UNESCAPED_UNICODE);
//            return ;
//        }

        $token=token();
        if( I('permission')=='')
        {
            $permission=0;
        }else{
            $permission = I("permission");
        }
        $user=array(
            'phonenumber'=>I('phonenumber'),
            'phonecode'=>$phonecode,
            'permission'=>$permission,
            'token'=>$token,
        );
        if( $user['phonenumber'] ==''|| $user['phonecode']=='')
        {
            $result=array(
                'code'=>'3',
                'message'=>'内容输入不全',
                'token'=>''
            );
        }else if($phonecode!=cookie($user["phonenumber"]))
        {
            $result=array(
                'code'=>'2',
                'message'=>'验证码错误',
                'phonenumber'=>$user["phonenumber"],
                'code1' => $phonecode,
                'code2' => cookie($user["phonenumber"]),
                'token'=>''
            );
        }else{
            $userinfo=array(
                'username'=>'',
                'password'=>'',
                'phonenumber'=>I('phonenumber'),
                'permission'=>'',
                'token'=>$token,
                'applytime'=>time()
            );
            //判断电话是否存在数据库中
            if(!($usermodel->where(array('phonenumber'=>$user['phonenumber']))->find())) {
                 $userid = $usermodel->add($userinfo);//将登录信息保存到用户表
                //注册成功初始化个人信息数据表
                $userdata=array(
                    'username'=>'用户'.date('Ymdhis',time()).rand(0,999),
                    'userid'=>$userid,
                    'token'=>$token,
                    'headurl'=>'http://ola.oss-cn-shenzhen.aliyuncs.com/aliyun/headimage/2016-09-23/1.jpg',
                    'create_date'=>date('Y-m-d H:i:s'),
                    'sex'=>'',
                    'birth'=>'',
                    'place'=>''
                );
                M('userdetail')->add($userdata);

                $result=array(
                    'code'=>'1',
                    'message'=>'登录成功',
                    'token'=>$token
                );
                //将token存入session中
                session('USER_LOGIN_TOKEN',$token);
            }else{
               $tokenfromdb= $usermodel->where(array('phonenumber'=>$user['phonenumber']))->select();
                $result=array(
                    'code'=>'1',
                    'message'=>'登录成功',
                    'token'=>$tokenfromdb[0]['token']
                );
                //将token存入session中
                session('USER_LOGIN_TOKEN',$token);
            }
        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }
    //接收验证码并判断手机号是否注册以及手机号是否可用
    public function phone(){
        $phonenumber=I('phonenumber');
        $apply=time();
        if(!preg_match("/^1[3578]\d{9}$/",$phonenumber))
        {
            $result=array(//手机号输入有误
                'code'=>'0',
                'message'=>'手机号有误',
                'phonecode'=>''
            );
        }else
        {
            $time=M('user')->where(array('phonenumber'=>$phonenumber))->field('applytime')->select();
            if($time)//电话已保存在数据库中
            {
                $obj=($apply-strtotime($time[0]['applytime'])) ;
                if($obj>=60)//大于一分钟
                {
                    $code=new \Message\Controller\IndexController();
                    cookie($phonenumber, mt_rand(1000, 9999),time()+60);
                    $code->sendDayuSmsPlus($phonenumber,(string)cookie($phonenumber));//发送短信
                    $result = array(
                        'code' => '1',
                        'message' => '已发送验证码',
                        'phnenumber' => $phonenumber,
                        'phonecode' => cookie($phonenumber),//验证码
                        'testcode' => cookie($phonenumber)
                    );
                    $timedata=array(
                        'applytime'=>date("Y-m-d H:i:s",$apply)
                    );
                     M('user')->where(array('phonenumber'=>$phonenumber))->save($timedata);//更新登录时间
                }else{//小于一分钟
                    $result = array(
                        'code' => '2',
                        'message' => '一分钟内不能重复获取验证码',
                        'phnenumber' => $phonenumber,
                    );
                }
            }else{//电话不在数据库中
                $code=new \Message\Controller\IndexController();
                cookie($phonenumber, mt_rand(1000, 9999));
                $code->sendDayuSmsPlus($phonenumber,cookie($phonenumber));//发送短信
                $result = array(
                    'code' => '1',
                    'message' => '已发送验证码',
                    'phnenumber' => $phonenumber,
                    'phonecode' => cookie($phonenumber),//验证码
                    'testcode' => cookie($phonenumber)
                );
            }

        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 个人信息操作部分
     */

    //返回已有个人信息
    public function getinfo(){
        $token=I('token');
        $filed=array('username','sex','birth','place','headurl');
        if(M('userdetail')->where(array('token'=>$token))->find()&&$token!='')
        {
            $data=M('userdetail')->where(array('token'=>$token))->field($filed)->select();
            $result=array(
                'username'=>$data[0]['username'],
                'sex'=>$data[0]['sex'],
                'birth'=>substr($data[0]['birth'], 0, 10),//截取字符串
                'place'=>$data[0]['place'],
                'headurl'=>$data[0]['headurl']
            );
        }else{
            $result=null;
        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    //对个人信息进行修改
    public function updateinfo(){
        $info=array(
            'token'=>I('token'),
            'username'=>I('username'),
            'sex'=>I('sex'),
            'birth'=>I('birth'),
            'place'=>I('place'),
//            'headurl'=>I('headurl')
        );
        if(M('userdetail')->where(array('token'=>$info['token']))->find()&&$info['token']!='')
        {
            M('userdetail')->where(array('token'=>$info['token']))->save($info);
            $result=array(
                'code'=>'1',
                'message'=>'修改成功'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'修改失败'
            );
        }

        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }


//测试用
    public function test(){
        $user=array(
            'phonenumber'=>I('phonenumber')
        );
        $tokenfromdb= M('user')->where(array('phonenumber'=>$user['phonenumber']))->select();
        $result=array(
            'code'=>'1',
            'message'=>'登录成功',
            'token'=>$tokenfromdb[0]['token']
        );
        echo json_encode($result);
    }
//根据用户useid，查询他的所有文章
    public function personpage(){
        $userid=(int)$_GET['userid'];
        $user= D('UserRelation');
        $result=$user->relation(true)->find($userid);
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }
}